﻿using System;
using System.Collections.Generic;
using System.Text;
using SyncCommon;
using System.IO;
using System.Text.RegularExpressions;

namespace SyncWebSite
{
    /// <summary>
    /// 好租
    /// </summary>
    public class SyncHaoZu : SyncHouseBase
    {
        private string cd;
        private string ptk;
        private string targetID = "";
        private string logintime = "1346058712095";
        private List<string> retImages = new List<string>();
        private List<string> retImagesext = new List<string>();
        private List<string> repeatimgs = new List<string>();
        private Dictionary<string, string> loginCookies = new Dictionary<string, string>();
        private string CityID = "11";
        private string CityShort = "sh";
        private string CityName = "shanghai";
        private Encoding inputCoding = Encoding.GetEncoding("GB2312");
        private Encoding outputCoding = Encoding.UTF8;
        public SyncHaoZu(string user, string password)
            : base(user, password)
        {

        }

        #region SyncHouseBase

        public override bool CheckLogin()
        {

            WebRequest request = new WebRequest("http://agent.haozu.com/my/login/", FormType.FormUrlEncode, inputCoding,outputCoding);
            request.Cookies = loginCookies;
            request.AllowRedirect = false;
            request.AddContent("mobile", UserName);
            request.AddContent("password", Password);
            request.AddContent("act", "post");
            string ret = request.SendWaitString();
            if (request.TransferLocation == "http://agent.haozu.com/my/home/")
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        //public override bool AddSaleHouse(HouseInfo info, ref string targetID)
        //{

        //}

        public override bool AddRentHouse(HouseInfo info, ref string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            //GetCityName(info);
            string error = "";
            try
            {
                if (!CheckLogin())
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登录失败");
                    return false;
                }
                else
                {
                    string errorInfor = "";
                    if (!CommonCheck(info, false, ref errorInfor))
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, errorInfor);
                        return false;
                    }
                    GetCityName(info);
                    WebRequest contentRequest = new WebRequest("http://agent.haozu.com/my/publish/");
                    contentRequest.Cookies = loginCookies;
                    string retHtml = contentRequest.GetResouceStr();
                    WebRequest request = new WebRequest("http://agent.haozu.com/my/publish/", FormType.MultiPart);
                    request.Cookies = loginCookies;
                    request.AllowRedirect = false;
                    request.AddContent("act", "post");
                    request.AddContent("type", "0");
                    request.AddContent("sproid", "0");
                    //小区信息
                    BuildingMapping(request, info, retHtml);

                    request.AddContent("nopost", "");
                    request.AddContent("repost", "");
                    request.AddContent("change_img_sort", "0");
                    request.AddContent("commdebug", "");

                    request.AddContent("renttype", GetHireType(info));
                    request.AddContent("roomnum", info.Room);
                    request.AddContent("hallnum", info.Hall);
                    request.AddContent("toilnetnum", info.WashRoom);
                    request.AddContent("floor", info.CurrentFloor);
                    request.AddContent("totalfloor", info.Floors);
                    request.AddContent("protype", GetHouseType(info.HouseType));
                    request.AddContent("fitment", GetDecoration(info.Decoration));
                    request.AddContent("toward", GetToward(info.Toward));

                    request.AddContent("sharetype", GetShareType(info));
                    request.AddContent("sharesex", "0");
                    request.AddContent("hezutoward", GetToward(info.Toward));
                    request.AddContent("areanum", info.Area);
                    request.AddContent("pricenum",info.MonthPrice);

                    request.AddContent("paymoneynum", GetPayment(info));
                    request.AddContent("is_ordinary","0");
                    request.AddContent("limit_rent", "0");
                    request.AddContent("oldpricenum", "0");


                    request.AddContent("title", info.Title);
                    request.AddContent("descript",info.Description);
                    request.AddContent("file", "");

                    request.AddContent("accept", "1");

                    UpdateCurrentStatus(StandardProgress.PosData);
                    SyncImage(info);
                    request.OnSendRequest += new WebRequest.OnSendRequestHandler(request_OnSendRequest);
                   
                    request.AddContent("imgcount", retImages.Count.ToString());
                    request.AddContent("defaultimg", "");

                    string input = request.SendWaitString();
                    if (!string.IsNullOrEmpty(request.TransferLocation))
                    {
                        request = new WebRequest(request.TransferLocation);
                        request.Cookies = loginCookies;
                        request.ReturnEncoding = outputCoding;
                        input = request.GetResouceStr();
                        if (input.Contains("您已成功发布"))
                        {
                            Regex regex = new Regex("<a href=\"\\S*?/(?<hid>\\w*?)\" title=\"浏览效果\"[\\S\\s]*?>浏览效果");
                            if (regex.IsMatch(input))
                            {
                                targetID = regex.Match(input).Groups["hid"].Value ?? "";
                                UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, "");
                                return true;
                            }
                        }
                        else if (input.Contains("您的房源已经成功发布"))
                        {
                            Regex regex2 = new Regex("<a href=\"\\S*?/(?<hid>\\w*?)\"\\s*?title='房源预览'[\\S\\s]*?>浏览效果");
                            Regex regex3 = new Regex("<a href=\"\\S*?/(?<hid>\\w*?)\"\\s*?title=\"浏览效果\"[\\S\\s]*?>浏览效果");
                            if (regex2.IsMatch(input))
                            {
                                targetID = regex2.Match(input).Groups["hid"].Value ?? "";
                            }
                            else if (regex3.IsMatch(input))
                            {
                                targetID = regex3.Match(input).Groups["hid"].Value ?? "";
                            }
                            UpdateCurrentStatus(StandardProgress.Sucess, GetImageError(info), targetID, "");
                            return true;
                        }
                        else if (input.Contains("您的房源没有发布成功") || input.Contains("您的房源已经被保存至草稿箱中"))
                        {
                            error = "今日发布次数已满，您的房源已经被保存至草稿箱中";
                        }
                    }
                }
            }
            catch (System.Net.WebException exp)
            {
                error = WebError;
            }
            catch (Exception exp)
            {
                LogCenter.Log("百姓网信息提交", exp);
                error = exp.Message;
            }
            if (string.IsNullOrEmpty(error))
            {
                error = "发布失败。发布消息格式不正确";
            }
            UpdateCurrentStatus(StandardProgress.Failed, error);
            return false;
        }

        void request_OnSendRequest(WebRequest sender, StringBuilder builder)
        {
            for (int i = 0; i < retImages.Count; i++)
            {
                builder.AppendLine(MultipartRender.seprate + MultipartRender.boundary);
                builder.AppendLine("Content-Disposition: form-data; name=\"" + "upload_imgs[]" + "\"");
                builder.AppendLine("");
                builder.AppendLine(retImages[i]);
                //request.AddContent("repeat_imgs[]", repeatimgs[i]);
            }
            sender.OnSendRequest -= request_OnSendRequest;
        }

        //public override bool DeleteSaleHouse(HouseInfo info, string targetID)
        //{

        //}

        public override bool DeleteRentHouse(HouseInfo info, string targetID)
        {
            UpdateCurrentStatus(StandardProgress.InitalData);
            try
            {

                if (CheckLogin())
                {
                    Random r = new Random();
                    WebRequest request = new WebRequest("http://agent.haozu.com/my/manager/W0QQactZoutline", FormType.FormUrlEncode);
                    request.Cookies = loginCookies;
                    request.AllowRedirect = false;
                    request.AddContent("subact", "del_prop");
                    request.AddContent("newrepub", "");
                    request.AddContent("price", "0,0");
                    request.AddContent("proid", "");

                    request.AddContent("price_min", "");
                    request.AddContent("price_max", "");
                    request.AddContent("portsort", "");
                    request.AddContent("proids[]", targetID);
                    UpdateCurrentStatus(StandardProgress.PosData);

                    string status = request.GetResouceStr();
                    status = HtmlHelper.DecodingJSON(status);

                    if (status.Contains("下线成功") && status.Contains("房源已到“下线房源”中"))
                    {
                        UpdateCurrentStatus(StandardProgress.Sucess, "");
                        return true;
                    }
                    else
                    {
                        UpdateCurrentStatus(StandardProgress.Failed, "删除失败");
                        LogCenter.LogMessage("好租网删除信息失败。提交值ID:" + targetID ?? "" + "返回值:" + status ?? "");
                        return false;
                    }
                }
                else
                {
                    UpdateCurrentStatus(StandardProgress.Failed, "登陆失败");
                    return false;
                }
            }
            catch (System.Net.WebException exp)
            {
                UpdateCurrentStatus(StandardProgress.Failed, WebError);
                return false;
            }
        }

        //public override bool RefreshSaleHouse(HouseInfo info, string targetID)
        //{

        //}
        //public override bool RefreshRentHouse(HouseInfo info, string targetID)
        //{

        //}
        #endregion

        #region HelpFunction

        private void DoPostImgHtml(string strHtml, out string _imgName)
        {
            _imgName = "";
            try
            {
                if ((strHtml ?? "") != "")
                {
                    Regex regex = new Regex("status\":\"ok\",[\\S\\s]*?,\"id\":\"(?<id>[\\S\\s]*?)\",");
                    if (regex.IsMatch(strHtml ?? ""))
                    {
                        _imgName = regex.Match(strHtml ?? "").Groups["id"].Value ?? "";
                    }
                }
            }
            catch
            {
            }
        }

        public void SyncImage(HouseInfo info)
        {
            retImages.Clear();
            retImagesext.Clear();
            errorImage = 0;
            if (info.Images != null && info.Images.Length > 0)
            {
                string status = "";
                foreach (string url in info.Images)
                {
                    try
                    {
                        WebRequest request = new WebRequest(url);
                        Stream stream = request.GetResouce();
                        string name = url.Substring(url.LastIndexOf('/') + 1);


                        request = new WebRequest("http://upd1.ajkimg.com/upload-haozu", FormType.MultiPart);
                        request.Cookies = loginCookies;
                        request.AddContent("ct", "text/html");
                        request.AddContent("rt", "http://agent.haozu.com/my/upload/image/");
                        request.AddFile(name, "file", stream);
                        string k = request.SendWaitString();
                        k = HtmlHelper.RemoveHtmlCode(HtmlHelper.DecodingJSON(k));

                        Regex regex = new Regex("status\":\"ok\",[\\S\\s]*?,\"id\":\"(?<id>[\\S\\s]*?)\",");
                        string imageName;
                        if (regex.IsMatch(k ?? ""))
                        {
                            imageName = regex.Match(k ?? "").Groups["id"].Value ?? "";
                            DoImgForm(imageName);
                        }
                        else
                        {
                            errorImage++;
                        }
                    }
                    catch
                    {
                        errorImage++;
                    }
                }
            }

        }

        private void DoImgForm(string imgName)
        {
            //屋内图形
            string str = "0*1*1*";
            string str2 = "1*";
            retImages.Add(str + imgName);
            retImagesext.Add(str2 + imgName);
        }

        private void BuildingMapping(WebRequest request, HouseInfo info,string html)
        {
            bool flag2 = false;
            string CommonID = "";
            string BlockID = "";
            string AreaID ="";
            string EstateName = info.Estate;
            string Address = info.LocalAddress;
       
                string siteBuildingName = info.Estate;
                string str2 = "";

                string strUrl = "http://agent.haozu.com/ajax/autocommlist/?query=" + siteBuildingName + "&p=0&cityid=" + CityID;
                WebRequest searchRequest = new WebRequest(strUrl);
                searchRequest.Cookies = loginCookies;
                string ret = searchRequest.GetResouceStr();
                string input = HtmlHelper.DecodingJSON(ret);
                Regex regex = new Regex("suggestions\":\\[(?<names>[\\S\\s]*?)\\],");
                int index = 0;
                if (regex.IsMatch(input))
                {
                    Regex regex2 = new Regex("\"(?<name>[\\S\\s]*?)<\\S*?>(?<address>[\\S\\s]*?)<\\S*?>\"");
                    if (regex2.IsMatch(regex.Match(input).Groups["names"].Value ?? ""))
                    {
                        MatchCollection matchs = regex2.Matches(regex.Match(input).Groups["names"].Value ?? "");
                        EstateName = matchs[0].Groups["name"].Value;
                        Address = matchs[0].Groups["address"].Value;
                        //if (matchs != null)
                        //{
                        //    foreach (Match match in matchs)
                        //    {
                        //        if ((match.Groups["name"].Value ?? "") == (siteBuildingName ?? ""))
                        //        {
                        //            EstateName = match.Groups["address"].Value ?? "";
                        //            break;
                        //        }
                        //        index++;
                        //    }
                        //    if (str2 == "")
                        //    {
                        //        foreach (Match match2 in matchs)
                        //        {
                        //            if ((match2.Groups["name"].Value ?? "") != "")
                        //            {
                        //                EstateName = match2.Groups["address"].Value ?? "";
                        //                break;
                        //            }
                        //            index++;
                        //        }
                        //    }
                        //    if (matchs.Count > 0)
                        //    {
                        //        flag2 = true;
                        //    }
                        //}
                    }
                }
                if (flag2)
                {
                    Regex regex3 = new Regex("commids\":\\[(?<commid>[\\S\\s]*?)\\],");
                    if (regex3.IsMatch(input))
                    {
                        string str6 = regex3.Match(input).Groups["commid"].Value ?? "";
                        string[] strArray = str6.Replace("\"", "").Split(new char[] { ',' });
                        if (strArray.Length > index)
                        {
                            CommonID = strArray[index] ?? "";
                        }
                    }
                    Regex regex4 = new Regex("areaids\":\\[(?<areaid>[\\S\\s]*?)\\],");
                    if (regex4.IsMatch(input))
                    {
                        string str7 = regex4.Match(input).Groups["areaid"].Value ?? "";
                        string[] strArray2 = str7.Replace("\"", "").Split(new char[] { ',' });
                        if (strArray2.Length > index)
                        {
                            AreaID = strArray2[index] ?? "";
                        }
                    }
                    Regex regex5 = new Regex("blockids\":\\[(?<blockid>[\\S\\s]*?)\\],");
                    if (regex5.IsMatch(input))
                    {
                        string str8 = regex5.Match(input).Groups["blockid"].Value ?? "";
                        string[] strArray3 = str8.Replace("\"", "").Split(new char[] { ',' });
                        if (strArray3.Length > index)
                        {
                            BlockID = strArray3[index] ?? "";
                        }
                    }
                }
                request.AddContent("commname", EstateName);
                request.AddContent("selected_commname", EstateName);
                request.AddContent("commid", CommonID);
                if ((((CommonID ?? "") == "") || ((AreaID ?? "") == "")) || ((BlockID ?? "") == ""))
                {
                    Regex reg = new Regex(@"<li id=""li_areaid_(?<districtID>\d*)"">"+info.LocalDistrict+"</li>");
                    Match ma = reg.Match(html);
                    if (ma.Success)
                    {
                        string streetID=ma.Groups["districtID"].Value;
                        request.AddContent("areaid",streetID);
                        WebRequest diduanRequest = new WebRequest(string.Format("http://agent.haozu.com/ajax/get_block/?flg=agent-li&areaid={0}&cityid=11&diff=1&time=0.501064419812504", streetID));
                        diduanRequest.Cookies = loginCookies;
                        string retDiduan = diduanRequest.GetResouceStr();
                        Regex diduanReg = new Regex(@"<li id=""li_blockid_(?<diduanID>\d*)"">"+info.LocalDiduan+"</li>");
                        Match diduanMa = diduanReg.Match(retDiduan);
                        if (diduanMa.Success)
                        {
                            request.AddContent("blockid", diduanMa.Groups["diduanID"].Value);
                        }
                        else
                        {
                            throw new UnFindDiduanException(info.LocalDiduan);
                        }
                        request.AddContent("address", info.LocalAddress);
                    }
                    else
                    {
                        throw new UnFindDistrictException(info.LocalDistrict);
                    }
                }
                else
                {
                    request.AddContent("areaid", AreaID);
                    request.AddContent("blockid", BlockID);
                    request.AddContent("address", Address);
                }
        }

       public void GetCityName(HouseInfo info)
        {
            CityName = PinyingConvert.Convert(info.City).ToLower();
            LogCenter.LogMessage("拼音转换，城市:" + info.City + " 拼音:" + CityName ?? "");
        }

        public string GetHireType(HouseInfo info)
        {
            //当前 0.单间出租 1.床位出租 2.整套出租
            //目标 1.整租 2.合租
            switch (info.HireType)
            {
                case "0":
                    return "2";
                case "1":
                    return "2";
                case "2":
                    return "1";
            }
            return "1";
        }

        public string GetHouseType(string type)
        {
            //当前 房屋类型.平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            //目标 公寓 =1,老公房 =2，新里洋房=3,别墅=4，酒店公寓=6，其他=5
            switch (type)
            {
                case "1":
                case "2":
                case "3":
                case "4":
                    return "1";
                case "5":
                    return "4";
                case "6":
                    return "5";
                default:
                    return "1";
            }
        }
        public string GetHouseType_Description(string type)
        {
            //当前 房屋类型.平房=1,普通住宅=2,商住两用=3,公寓=4,别墅=5,其他=6
            //目标 公寓 =1,老公房 =2，新里洋房=3,别墅=4，酒店公寓=6，其他=5
            switch (type)
            {
                case "1":
                case "2":
                case "3":
                case "4":
                    return "公寓";
                case "5":
                    return "别墅";
                case "6":
                    return "其他";
                default:
                    return "公寓";
            }
        }
        public string GetDecoration(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标 毛坯 =1,简单装修=2,精装修=3,豪华装修=4
            switch (dec)
            {
                case "1":
                    return "1";
                case "2":
                    return "2";
                case "3":
                    return "3";
                case "4":
                    return "4";
                default:
                    return "2";
            }
        }
        public string GetDecoration_Description(string dec)
        {
            //当前 1:毛胚 2:简装 3:精装 4:豪装
            //目标 毛坯 =1,简单装修=2,精装修=3,豪华装修=4
            switch (dec)
            {
                case "1":
                    return "毛坯";
                case "2":
                    return "简单装修";
                case "3":
                    return "精装修";
                case "4":
                    return "豪华装修";
                default:
                    return "简单装修";
            }
        }
        public string GetToward(string toward)
        {
            //当前 1:东 2:南 3:西 4:北 5:南北 6:东西 7:东南 8:西南 9:东北 10:西北 11:其他
            //目标 东=1,南=2, 西=3,北=4,南北=5,东西=6,东南=7,西南=8,东北=9,西北=10,不知道朝向=11
            return toward;
        }
        public string GetToward_Description(string toward)
        {
            //当前 1:东 2:南 3:西 4:北 5:南北 6:东西 7:东南 8:西南 9:东北 10:西北 11:其他
            //目标 东=1,南=2, 西=3,北=4,南北=5,东西=6,东南=7,西南=8,东北=9,西北=10,不知道朝向=11
            switch (toward)
            { 
                case "1":
                    return "东";
                case "2":
                    return "南";
                case "3":
                    return "西";
                case "4":
                    return "北";
                case "5":
                    return "南北";
                case "6":
                    return "东西";
                case "7":
                    return "东南";
                case "8":
                    return "西南";
                case "9":
                    return "东北";
                case "10":
                    return "西北";
                case "11":
                    return "不知道朝向";
            }
            return "不知道朝向";
        }
        public string GetPayment(HouseInfo info)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 1.面议, 2.付3押1, 3.付1押1, 4.付2押1, 5.付1押2, 6. 年付不押, 7.半年付不押 
            switch (info.PayType)
            {
                case "0":
                    return "1";
                case "1":
                    return "3";
                case "2":
                    return "4";
                case "3":
                    return "2";
                case "4":
                    return "1";
            }
            return "1";
        }
        public string GetPayment_Description(HouseInfo info)
        {
            //当前 1:付一押一 2:付二押一 3:付三押一 4:付六押一
            //目标 1.面议, 2.付3押1, 3.付1押1, 4.付2押1, 5.付1押2, 6. 年付不押, 7.半年付不押 
            switch (info.PayType)
            {
                case "0":
                    return "面议";
                case "1":
                    return "付1押1";
                case "2":
                    return "付2押1";
                case "3":
                    return "付3押1";
                case "4":
                    return "面议";
            }
            return "面议";
        }
        
        public string GetShareType( HouseInfo info)
        {
            //目标 5=单间,3=隔断,2=床位
            switch (info.HireType)
            { 
                case "0":
                    return "5";
                case"1":
                    return "2";
                case "2":
                    return "5";
                default:
                    return "5";
            }
        }

        #endregion

        #region 编辑功能
        public override bool OpenEidt(WebBrowserOp op, HouseInfo info)
        {
            try
            {
                op.Navigate("http://agent.haozu.com/my/login/");
                op.HouseInformation = info;
                op.Completed += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(op_Rent_Completed);
            }
            catch
            {
                op.Navigate("http://sh.haozu.com/");
            }
            return true;
        }
        int tryTime = 0;
        void op_Rent_Completed(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            
            WebBrowserOp cl = sender as WebBrowserOp;
            HouseInfo info = cl.HouseInformation;
            if (cl.innerBrowser.Url.OriginalString.Contains("http://agent.haozu.com/my/home"))
            {
                cl.RaiseOpByAttribute("_soj", "iconpublish", "click");
                return;
            }

            if (cl.innerBrowser.Url.OriginalString.Contains("http://agent.haozu.com/my/login/"))
            {
                if (tryTime > 1)
                {
                    tryTime = 0;
                    return;
                }
                else
                {
                    tryTime++;
                }
                cl.SetValueByID("mobile", UserName);
                cl.SetValueByID("password", Password);
                cl.RaiseOpByID("sub", "click");
                return;
            }

            if (cl.innerBrowser.Url.OriginalString.Contains("http://agent.haozu.com/my/publish/"))
            {

                cl.SetValueByID("commname", info.Estate);
                cl.SelectByID_Value("ddl_Area", info.LocalDistrict);
                cl.SetValueByID("pricenum", info.MonthPrice);
                cl.SetValueByID("areanum", info.Area);
                cl.SetValueByID("roomnum", info.Room);
                cl.SetValueByID("hallnum", info.Hall);
                cl.SetValueByID("toilnetnum", info.WashRoom);

                cl.SetValueByID("floor", info.CurrentFloor);
                cl.SetValueByID("totalfloor", info.Floors);

                cl.SetHtmlByIDWithoutBlank("selectBox_protype_txt", GetHouseType_Description(info.HouseType));
                cl.SetValueByName_BigBrother("protype", GetHouseType(info.HouseType));

                cl.SetHtmlByIDWithoutBlank("selectBox_fitment_txt", GetDecoration_Description(info.Decoration));
                cl.SetValueByName_BigBrother("fitment", GetDecoration(info.Decoration));

                cl.SetHtmlByIDWithoutBlank("selectBox_toward_txt", GetToward_Description(info.Toward));
                cl.SetValueByName_BigBrother("toward", GetToward(info.Toward));


                cl.SetHtmlByIDWithoutBlank("selectBox_paymoneynum_txt", GetPayment_Description(info));
                cl.SetValueByName_BigBrother("paymoneynum", GetPayment(info));

                cl.SetValueByID("title", info.Title);


                cl.SetCKEditorHtml(info.Description);

            }
        }
        #endregion
    }
}
